import React from 'react';
import style from './index.less';
import { Modal, Spin } from 'antd';
import { getDvaApp } from 'umi';
// components
import TRNotification from '@/utils/notification';
import { createFromIconfontCN, CloseOutlined } from '@/utils/antdIcons';
import { getMenuIconList } from '@/services/power';
import { HttpCode } from '@/utils/contacts';
import { TITLE_TYPE } from './helper';

const ChangeIconModal = ({ onPress, type, firstMenuId }) => {
  const [visible, setVisible] = React.useState(false); // modal
  const [loading, setLoading] = React.useState(false); // LOADING
  const [iconList, setIconList] = React.useState([]); // 步骤进度
  const _getMenuIconList = async () => {
    setLoading(true);
    const res = await getMenuIconList();
    setLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setIconList(res.data);
    } else {
      setIconList([]);
    }
  };

  React.useEffect(() => {
    setVisible(true);
    _getMenuIconList();
  }, []);

  const _onCancel = () => {
    onPress({ index: 0 });
    setVisible(false);
  };

  const _clickIcon = (icon) => {
    onPress({
      icon,
      firstMenuId,
    });
  };
  const iconUrl = getDvaApp()?._store?.getState()?.user?.iconUrl || '';
  const MyIcon = createFromIconfontCN({
    scriptUrl: iconUrl,
  });
  return (
    <Modal
      centered={true}
      visible={visible}
      onCancel={_onCancel}
      footer={false}
      maskClosable={false}
      width={527}
      title={TITLE_TYPE[type]}
      closeIcon={<CloseOutlined style={{ fontSize: 16, color: 'var(--font)' }} />}
      size="small"
    >
      <Spin spinning={loading}>
        <div className={style.iconModel}>
          {iconList.map((_icon, idx) => (
            <div key={idx}>
              <MyIcon
                style={{ fontSize: 24 }}
                type={_icon.icon}
                onClick={() => _clickIcon(_icon.icon)}
              />
            </div>
          ))}
        </div>
      </Spin>
    </Modal>
  );
};

class IconModal {
  __key__ = '';
  show = (firstMenuId, type) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ChangeIconModal
            onPress={(obj) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(obj);
            }}
            firstMenuId={firstMenuId}
            type={type}
          />
        ),
        dismiss: this.dismiss,
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const TRIconModal = new IconModal();
export default TRIconModal;
